﻿#region Copyright and Licensing Notice
// Copyright (C) 2011 Steven Bosnick
// 
// This program is open source software; you can redistribute it 
// and/or modifiy it under the terms of the Eclipse Public License,
// version 1.0.
// 
// This program is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A 
// PARTICULAR PURPOSE. See the Eclipse Public License for more
// details.
// 
// You should have received a copy of the Eclipse Public License 
// along with this program; if not, you can find a copy at
// "http://www.opensource.org/licenses/eclipse-1.0.php".
#endregion
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using BitwiseOre.SharedMemory.Core.Common;

namespace BitwiseOre.SharedMemory.Core
{
    internal sealed class Acceptor : IAcceptor
    {
        private readonly IListenerQueue _listenerQueue;
        private readonly IEventWaitHandleFactory _eventFactory;
        private readonly Func<TimeSpan, ITimeoutHelper> _timeoutHelperFactory;

        public Acceptor(IListenerQueue listenerQueue, IEventWaitHandleFactory eventFactory,
                        Func<TimeSpan, ITimeoutHelper> timeoutHelperFactory)
        {
            _listenerQueue = listenerQueue;
            _eventFactory = eventFactory;
            _timeoutHelperFactory = timeoutHelperFactory;
        }

        public Task<T> Accept<T>(TimeSpan timeOut, Func<Guid, T> factory)
            where T : class, IDisposable
        {
            var helper = _timeoutHelperFactory(timeOut);

            return RepeatedAccept(helper, factory).LastResult();
        }

        private IEnumerable<Task<T>> RepeatedAccept<T>(ITimeoutHelper timeoutHelper, Func<Guid, T> factory)
            where T : class, IDisposable
        {
            Task<T> task;

            do
            {
                task = _listenerQueue.Dequeue(timeoutHelper.RemainingTime)
                    .Then(guid => CreateAndSignal(guid, factory));

                yield return task;
            } while (task.Result == null);
        }

        private T CreateAndSignal<T>(Guid guid, Func<Guid, T> factory)
            where T : class, IDisposable
        {
            using (var eventhandle = _eventFactory.Create(guid.ToString()))
            {
                if (eventhandle == null) return null;

                var result = factory(guid);
                try
                {
                    eventhandle.Value.Set();
                }
                catch
                {
                    if (result != null) result.Dispose();
                    throw;
                }
                return result;
            }
        }

        public Task WaitFor(TimeSpan timeOut)
        {
            return _listenerQueue.WaitNotEmpty(timeOut);
        }
    }
}